#include<string>
#include<vector>

using namespace std;

class Solution {
public:
    vector<string> fullJustify(vector<string>& words, int maxWidth) {
        string tem;
        vector<string> v;
        for (int i = 0; i < words.size(); i++)
        {
            if ((tem.size() + words[i].size()) <= maxWidth)
            {
                tem += words[i];
                tem += ' ';
                continue;
            }
            else
            {
                i--;
                if (tem.size() == (maxWidth + 1))
                {
                    tem.pop_back();
                    break;
                }
                tem.pop_back();
                int pos = 0;
                int count = 1;
                while (1)
                {
                    while ((pos = tem.find(' ', pos)) != string::npos)
                    {
                        tem.insert(pos, 1, ' ');
                        if (tem.size() == maxWidth)
                        {
                            break;
                        }
                        pos += (count + 1);
                    }
                    if (pos == string::npos && tem.size() == maxWidth)
                    {
                        break;
                    }
                    if (pos == string::npos)
                    {
                        pos = 0;
                        count++;
                        continue;
                    }
                    if (tem.size() == maxWidth)
                    {
                        break;
                    }
                }
            }
            v.push_back(tem);
            tem.clear();
        }
        v.push_back(tem);
        if (v[(v.size() - 1)].size() < 16)
        {
            v[(v.size() - 1)].push_back(' ');
        }
        return v;
    }
};

int main()
{
    Solution s;
    vector<string> v = { {"This"}, {"is"}, {"an"}, {"example"}, {"of"}, {"text"}, {"justification."} };
    s.fullJustify(v, 16);
    return 0;
}